package com.m4f.city.web.controller;

import java.security.Principal;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.oauth2.provider.verification.BasicUserApprovalFilter;
import org.springframework.security.oauth2.provider.verification.VerificationCodeAuthenticationToken;
import org.springframework.security.oauth2.provider.verification.VerificationCodeFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.m4f.city.business.domain.Application;
import com.m4f.city.business.domain.Company;
import com.m4f.city.business.domain.InternalUser;
import com.m4f.city.business.domain.oauth2.OAuth2AccessTokenDS;
import com.m4f.city.business.security.InternalUserDetailService;
import com.m4f.gaeweb.exception.M4FException;
import com.m4f.gaeweb.web.utils.StackTraceUtil;

@Controller
@Secured({InternalUserDetailService.ROLE_USER, InternalUserDetailService.ROLE_MANAGER})
@RequestMapping("/oauth")
public class OAuthController extends BaseController {
	
	private static final Logger LOGGER = Logger.getLogger(OAuthController.class.getName());
	
	@RequestMapping("/confirm_access")
	public String getConfirmPage(HttpServletRequest request, HttpSession session, Principal principal, Model model) throws M4FException {
		
		InternalUser user = getInternalUser(principal);
		OAuth2AccessTokenDS accesTokenDS = null;
		VerificationCodeAuthenticationToken token = (VerificationCodeAuthenticationToken) session.getAttribute("org.springframework.security.oauth2.provider.webserver.DefaultClientAuthenticationCache#SAVED_AUTH");
		try {
			accesTokenDS = this.serviceLocator.getOAuth2TokensService().getAccessToken(user.getId(), token.getClientId());
		} catch(Exception e) {
			LOGGER.log(Level.SEVERE, StackTraceUtil.getStackTrace(e)); 
		}
		try {
			if(accesTokenDS != null) {
				return getRedirect(VerificationCodeFilter.DEFAULT_PROCESSING_URL+"?"+BasicUserApprovalFilter.DEFAULT_APPROVAL_REQUEST_PARAMETER+"=true", null);
			} else {
				Application app = this.serviceLocator.getApplicationService().getAppliaction(token.getClientId());
				model.addAttribute("client", app);
				Company company = this.serviceLocator.getCompanyService().getObjectById(app.getCompanyId());
				model.addAttribute("company", company);
				return "oauth.access.confirm";
			}		
		} catch(Exception e) {
			LOGGER.log(Level.SEVERE, StackTraceUtil.getStackTrace(e)); 
			return "oauth.access.error";
		}
		
		/*
		try {
			// TODO try to get other way to obtain the client_id 
			//VerificationCodeAuthenticationToken token = (VerificationCodeAuthenticationToken) session.getAttribute("org.springframework.security.oauth2.provider.webserver.DefaultClientAuthenticationCache#SAVED_AUTH");
			Application app = this.serviceLocator.getApplicationService().getAppliaction(token.getClientId());
			model.addAttribute("client", app);
		} catch(Exception e) {
			LOGGER.log(Level.SEVERE, StackTraceUtil.getStackTrace(e)); // TODO redirect to oauth page error
		}
		return "oauth.access.confirm";*/
	}
}
